﻿using AutoTest.Business.IServices.Common;
using AutoTest.Common.Extension;
using AutoTest.Framework.Ioc;
using Microsoft.AspNetCore.Hosting;
using Serilog;

namespace AutoTest.Business.Services.Common
{
    /// <summary>
    /// 文件服务
    /// </summary>
    public class FileService(IWebHostEnvironment hostingEnvironment) : IFileService,IScoped
    {
        /// <summary>
        /// 主机目录
        /// </summary>
        protected IWebHostEnvironment _hostingEnvironment = hostingEnvironment;

        /// <summary>
        /// 保存文件到服务器
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="strBase64"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public async Task<string> SaveFileToServer(string fileName, string strBase64, string target)
        {
            string ext = Path.GetExtension(fileName);
            if (ext.IsEmpty())
            {
                ext = ".png";
            }
            string baseDirectory = _hostingEnvironment.WebRootPath; ;
            string filename = $"{Guid.NewGuid().ToString("N")}{ext}";
            string temp = DateTime.Now.ToString("yyyyMM");
            string path = Path.Combine(baseDirectory, "upload", target, temp, filename);
            string directory = Path.GetDirectoryName(path)!;
            if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
            string relativePath = $"/upload/{target}/{temp}/{filename}";
            try
            {
                byte[] buffer = Convert.FromBase64String(strBase64);
                var fs = new FileStream(path, FileMode.CreateNew);
                await fs.WriteAsync(buffer, 0, buffer.Length);
                fs.Close();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
                relativePath = string.Empty;
            }
            return relativePath;
        }

        /// <summary>
        /// 保存流文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="stream"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public async Task<string> SaveFileStream(string fileName, Stream stream, string target)
        {

            string ext = Path.GetExtension(fileName);
            if (ext.IsEmpty())
            {
                ext = ".png";
            }
            string baseDirectory = _hostingEnvironment.WebRootPath; ;
            string filename = $"{Guid.NewGuid().ToString("N")}{ext}";
            string temp = DateTime.Now.ToString("yyyyMM");
            string path = Path.Combine(baseDirectory, "upload", target, temp, filename);
            string directory = Path.GetDirectoryName(path)!;
            if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
            string relativePath = $"/upload/{target}/{temp}/{filename}";
            try
            {
                byte[] buffer = new byte[1024];
                int index = 0;
                using var fs = new FileStream(path, FileMode.CreateNew);
                while ((index = await stream.ReadAsync(buffer, 0, 1024)) > 0)
                {
                    await fs.WriteAsync(buffer, 0, index);
                }

            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
                relativePath = string.Empty;
            }
            return relativePath;
        }
    }
}
